package com.example.testapplication;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class BroadcastReceiverActivity extends AppCompatActivity {

    private ImoocBroadcastReceiver broadcastReceiver;
    private EditText inputEditText;
    private Button sendBroadcastButton;
    private TextView resultTextView;
    public static final String MY_ACTION = "com.imooc.demo.afdsabfdaslj";
    public static final String BROADCAST_CONTENT = "broadcast_content";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcastreceiver);

        inputEditText = findViewById(R.id.inputEditText);
        sendBroadcastButton = findViewById(R.id.sendBroadcastButton);
        resultTextView = findViewById(R.id.resultTextView);

        // 新建一个广播接收器
        broadcastReceiver = new ImoocBroadcastReceiver(resultTextView);

        // 注册广播接收器


        // 要接收哪些广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
        intentFilter.addAction(MY_ACTION);

        // 注册广播接收器
        registerReceiver(broadcastReceiver,intentFilter);

        sendBroadcastButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // 新建广播
                Intent intent = new Intent(MY_ACTION);
                // 放入广播要携带的数据
                intent.putExtra(BROADCAST_CONTENT, inputEditText.getText().toString());
                sendBroadcast(intent); // 发送广播
            }
        });


    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器，不然会导致内存泄露
        if(broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);
        }
    }
}
